#! /usr/bin/env node

import { EnumPublishType } from "../data/Config";

import fs = require('fs');
import path = require("path");
import inquirer = require("inquirer");
import chalk = require("chalk");

const templatePath = path.join(__dirname, '../../assets/config/');

function askInput(msg: string, key: string) {
    let questions = [
        {
            type: "input",
            name: key,
            message: msg
        },
    ];
    return inquirer.prompt(questions);
};

function askConfirm(msg: string, key: string) {
    let questions = [
        {
            type: "confirm",
            name: key,
            message: msg
        },
    ];
    return inquirer.prompt(questions);
};

function askPlat() {
    let questions = [
        {
            type: "rawlist",
            name: "type",
            message: "请选择发布平台?",
            choices: [
                { name: '微信小游戏', value: EnumPublishType.WxMiniGame },
                { name: 'web平台', value: EnumPublishType.Web },
                { name: 'FaceBook', value: EnumPublishType.FaceBook },
                { name: '安卓Apk', value: EnumPublishType.WebApk },
                { name: '手Q', value: EnumPublishType.QQ },
                { name: 'Vivo小游戏', value: EnumPublishType.Vivo },
                { name: 'Oppo小游戏', value: EnumPublishType.Oppo },
                { name: '百度小游戏', value: EnumPublishType.Baidu },
                { name: '头条', value: EnumPublishType.TouTiao },
                { name: '华为快游戏', value: EnumPublishType.HuaWei },
                { name: 'BiliBili小游戏', value: EnumPublishType.Bili },
                { name: '小米快游戏', value: EnumPublishType.XiaoMi },
            ],
            default: 0,
            pageSize: 20,
            loop: false
        }
    ];
    return inquirer.prompt(questions);
};

const KEY_NAME = {
    name: {
        type: 'input',
        label: "请输入项目名称",
        fatherNode: 'content'
    },
    appId: {
        type: 'input',
        label: "请输入appId/包名",
        fatherNode: 'content',
        platType: [
            EnumPublishType.QQ, EnumPublishType.WxMiniGame, EnumPublishType.Vivo, EnumPublishType.Oppo, EnumPublishType.Baidu, EnumPublishType.TouTiao, EnumPublishType.HuaWei, EnumPublishType.Bili,
            EnumPublishType.KuGou,EnumPublishType.XiaoMi
        ]
    },
    plat: {
        type: 'input',
        label: "请输入渠道号",
        fatherNode: '',
        platType: [
            EnumPublishType.FaceBook, EnumPublishType.Web
        ]
    },
    chkRelease: {
        type: 'confirm',
        label: "是否正式版本",
        fatherNode: 'content',
        platType: [
            EnumPublishType.Web, EnumPublishType.Vivo, EnumPublishType.Oppo, EnumPublishType.HuaWei,EnumPublishType.XiaoMi
        ]
    },
    toPath: {
        type: 'input',
        label: "请输入导出路径",
        fatherNode: '',
    },
    compressImg: {
        type: 'confirm',
        label: "是否压缩图片",
        fatherNode: '',
    },
    localRes: {
        type: 'confirm',
        label: "是否使用本地资源",
        fatherNode: '',
    },
    Debug: {
        type: 'confirm',
        label: "是否Debug",
        fatherNode: 'config',
    },
    CdnUrl: {
        type: 'input',
        label: "请输入资源路径",
        fatherNode: 'config',
    },
    adId: {
        type: 'input',
        label: "请输入adId",
        fatherNode: 'config',
        platType: [
            EnumPublishType.WxMiniGame
        ]
    },
    bannerId: {
        type: 'input',
        label: "请输入bannerId",
        fatherNode: 'config',
        platType: [
            EnumPublishType.WxMiniGame
        ]
    },
    icon: {
        type: 'input',
        label: "请输入ICON路径",
        fatherNode: 'content',
        platType: [
            EnumPublishType.Vivo, EnumPublishType.Oppo, EnumPublishType.HuaWei,EnumPublishType.XiaoMi
        ]
    },
    cert: {
        type: 'input',
        label: "请输入密钥路径",
        fatherNode: 'content',
        platType: [
            EnumPublishType.Vivo, EnumPublishType.Oppo, EnumPublishType.HuaWei,EnumPublishType.XiaoMi
        ]
    },
    versionCode: {
        type: 'input',
        label: "请输入数字版本号",
        fatherNode: 'content',
        platType: [
            EnumPublishType.Vivo, EnumPublishType.Oppo, EnumPublishType.HuaWei,EnumPublishType.XiaoMi
        ]
    },
    minSdkVersion: {
        type: 'input',
        label: "请输入最低sdk版本",
        fatherNode: 'content',
        platType: [
            EnumPublishType.Vivo, EnumPublishType.Oppo, EnumPublishType.HuaWei,EnumPublishType.XiaoMi
        ]
    },
    apkPath: {
        type: 'input',
        label: "请输入安卓路径",
        fatherNode: 'content',
        platType: [
            EnumPublishType.WebApk
        ]
    },
}

function logHelp() {
    console.log('\n');
    console.log("Usage: template [options]\n");
    console.log("Options:");
    console.log("   -a, --add          新增配置模板");
    console.log("   -d, --delete       删除配置模板");
    console.log("   -u, --update       修改配置模板");
    console.log("   -c, --check        查看配置模板");
    console.log('\n');
}

async function createTempl(filePath: string, platType: number, projectVo?: any) {
    let project = {
        name: '',
        type: 1,
        publish: {
            fromPath: path.join(process.cwd(), '/bin/'),
            type: platType,
            content: {},
            config: {},
        },
    }

    let questions = [];
    for (let i in KEY_NAME) {
        let value = KEY_NAME[i];
        if (!value['platType'] || value['platType'].indexOf(platType) != -1) {
            let fatherNode = KEY_NAME[i]['fatherNode'];
            let question = {
                type: value['type'],
                name: i,
                message: value['label'],
            }

            if (projectVo) {
                question['default'] = fatherNode ? projectVo['publish'][fatherNode][i] : projectVo['publish'][i];
            }

            questions.push(question);
        }
    }

    let result = await inquirer.prompt(questions);
    for (let i in result) {
        let fatherNode = KEY_NAME[i]['fatherNode'];
        if (fatherNode) {
            project['publish'][fatherNode][i] = result[i];
        }
        else {
            project['publish'][i] = result[i];
        }
        if (i == 'name') {
            project['name'] = result[i]
        }
    }

    console.log(chalk.yellow("======================================================="));
    console.log(chalk.white.bgBlueBright.bold('配置模板内容如下：'))
    console.log(project);
    console.log(chalk.yellow("======================================================="));

    project['publish']['config'] = JSON.stringify(project['publish']['config']);

    return {
        filePath: filePath,
        projectVo: project
    };
}

async function checkTempl() {
    let dirArray = fs.readdirSync(templatePath);
    let nameList = [];
    for (let i = 0; i < dirArray.length; i++) {
        nameList.push(dirArray[i].split('.')[0]);
    }

    if (nameList.length <= 0) {
        console.log("暂无模板");
        return null;
    }

    let questions = [
        {
            type: "rawlist",
            name: "fileName",
            message: "请选择配置模板?",
            choices: nameList,
            default: 0,
            pageSize: 100,
            loop: false
        }
    ];
    let fileName = await inquirer.prompt(questions);

    let filePath = path.join(templatePath, fileName['fileName'] + '.cfg');
    let str = fs.readFileSync(filePath);
    let projectVo = JSON.parse(str.toString());
    projectVo['publish']['config'] = JSON.parse(projectVo['publish']['config']);

    console.log(chalk.yellow("======================================================="));
    console.log(chalk.white.bgBlueBright.bold('配置模板内容如下：'))
    console.log(projectVo);
    console.log(chalk.yellow("======================================================="));

    return {
        filePath: filePath,
        projectVo: projectVo
    };
}

async function run(argv) {

    if (argv[0]) {
        let argv1 = argv[0].toLowerCase();
        if (argv1 === '-a' || argv1 === '--add') {
            let fileName = await askInput('请输入模板名称', 'fileName');
            let filePath = path.join(templatePath, fileName['fileName'] + '.cfg');
            if (fs.existsSync(filePath)) {
                console.log("同名配置文件已存在");
                return;
            }

            let plat = await askPlat();
            let resultCreate = await createTempl(filePath, plat['type']);
            let confirmSave = await askConfirm('请确认是否保存模板', 'isSave');
            if (confirmSave['isSave']) {
                fs.writeFileSync(resultCreate['filePath'], JSON.stringify(resultCreate['projectVo']));
                console.log(chalk.white.bgGreenBright.bold('操作完成！'));
            }
            else {
                console.log(chalk.white.bgRedBright.bold('操作终止！'));
            }
        }
        else if (argv1 === '-u' || argv1 === '--update') {
            let resultCheck = await checkTempl();
            if (!resultCheck) {
                return;
            }
            let confirmUpdate = await askConfirm('请确认是否继续修改模板', 'isUpdate');
            if (confirmUpdate['isUpdate']) {
                let resultCreate = await createTempl(resultCheck['filePath'], resultCheck['projectVo']['publish']['type'], resultCheck['projectVo']);
                let confirmSave = await askConfirm('请确认是否保存模板', 'isSave');
                if (confirmSave['isSave']) {
                    fs.writeFileSync(resultCreate['filePath'], JSON.stringify(resultCreate['projectVo']));
                    console.log(chalk.white.bgGreenBright.bold('操作完成！'));
                }
                else {
                    console.log(chalk.white.bgRedBright.bold('操作终止！'));
                }
            }
            else {
                console.log(chalk.white.bgRedBright.bold('操作终止！'));
            }
        }
        else if (argv1 === '-d' || argv1 === '--delete') {
            let resultCheck = await checkTempl();
            if (!resultCheck) {
                return;
            }
            let confirmDelete = await askConfirm('请确认是否继续删除模板', 'isDelete');
            if (confirmDelete['isDelete']) {
                fs.unlinkSync(resultCheck['filePath']);
                console.log(chalk.white.bgGreenBright.bold('操作完成！'));
            }
            else {
                console.log(chalk.white.bgRedBright.bold('操作终止！'));
            }

        }
        else if (argv1 === '-c' || argv1 === '--check') {
            let resultCheck = await checkTempl();
            if (!resultCheck) {
                return;
            }
            console.log(chalk.white.bgGreenBright.bold('操作完成！'));
        }
        else {
            logHelp();
        }
    }
    else {
        logHelp();
    }
}

run(process.argv.slice(2));

